//
//  ZYCSchoolAttendanceViewController.m
//  ZDSC
//
//  Created by 张威 on 2021/10/19.
//

#import "ZYCSchoolAttendanceViewController.h"
#import "BTImageTitleButton.h"
#import "PullDownMenuView.h"
#import <FSCalendar.h>
#import "ZYCPullDownMenuViewController.h"
#import "ZYCAttendanceSummaryViewController.h"
#import "ZYCSchoolAttendanceStaticsBottomView.h"
#import "ZYCCommonBaseModel.h"
#import "ZYCSchoolAttendanceStatisticsModel.h"
#import "LunarFormatter.h"
#import "ZYCCalendarCell.h"


@interface ZYCSchoolAttendanceViewController ()<PullDownMenuViewDataSource,FSCalendarDelegate,FSCalendarDataSource,UIGestureRecognizerDelegate>

@property (nonatomic, strong) FSCalendar *calendar;
@property (nonatomic, strong) BTImageTitleButton *rightButton;
@property (nonatomic, strong) PullDownMenuView *menuView;
@property (nonatomic, strong) UIButton *previousButton;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) ZYCSchoolAttendanceStaticsBottomView *staticsBottomView;

@property (nonatomic, strong) NSCalendar *gregorian;
@property (nonatomic, strong) LunarFormatter *lunarFormatter;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) NSArray *viewControlls;
@property (nonatomic, strong) NSArray *postArr;



@property (nonatomic, copy) NSString *attendanceDate;
@property (nonatomic, copy) NSString *postId;
@property (nonatomic, copy) NSString *postName;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;

@property (nonatomic, strong) NSArray *normalArr;
@property (nonatomic, strong) NSArray *exceptArr;
@property (nonatomic, strong) NSArray *workOvertimeArr;



@end

@implementation ZYCSchoolAttendanceViewController
#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"学校考勤统计";
    self.view.backgroundColor = HEX_RGB(@"#FAFAFA");
    self.gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    self.lunarFormatter = [[LunarFormatter alloc] init];
    [self setupUI];
    self.attendanceDate = [self.dateFormatter stringFromDate:[NSDate date]];

    self.postId = @"0";
    self.postName = @"全体教职工";
    [self getAllpostList];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithNot:) name:UpdateMenuTitleNote object:nil];
    
    [self loadAllSchoolMonthCalendarAttendance];
    // 学校天考勤统计
    [self loadDayStatistics];
}



- (void)dealWithNot:(NSNotification *)note {
    if (![self.viewControlls containsObject:note.object]) {
        return;
    }
    NSInteger col = [self.viewControlls indexOfObject:note.object];
    NSArray *allValues = note.userInfo.allValues;
//    // 不需要设置标题,字典个数大于1，或者有数组
    if (allValues.count > 1 || [allValues.firstObject isKindOfClass:[NSArray class]]) return ;
    if (col == 0) {
        ZYCCommonBaseModel *model = allValues.firstObject;
        self.postId = model.nameId;
        self.postName = model.name;
        [self loadAllSchoolMonthCalendarAttendance];
    }
}


#pragma mark - 网络请求
// 获取全部岗位
- (void)getAllpostList{
    [[URLManager sharedURLManager] getUrlString:Appliance_Post_TchOptionSelect requestService:RequestServiceSystem parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                self.postArr = [NSArray yy_modelArrayWithClass:[ZYCCommonBaseModel class] json:responseObject[@"body"]];
                self.menuView.dataSource = self;
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

// 获取日历数据
- (void)loadAllSchoolMonthCalendarAttendance{
    NSDictionary *params = @{
        @"attendanceDate":self.attendanceDate,
        @"postId":self.postId
    };
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TeacherMonthListIOS requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                self.normalArr = responseObject[@"body"][@"attendanceIosListZC"];
                self.workOvertimeArr = responseObject[@"body"][@"attendanceIosListJB"];
                self.exceptArr = responseObject[@"body"][@"attendanceIosListYC"];
                [self.calendar reloadData];
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

//
- (void)loadDayStatistics{
    NSDictionary *params = @{
        @"attendanceDate":self.attendanceDate,
        @"postId":self.postId
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TeacherDayCensus requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                ZYCSchoolAttendanceStatisticsModel *model = [ZYCSchoolAttendanceStatisticsModel yy_modelWithDictionary:responseObject[@"body"]];
                self.staticsBottomView.model = model;
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
    
}
#pragma mark - private method

- (void)setupUI{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    [self.view addSubview:self.menuView];
    [self.view addSubview:self.calendar];
    [self.view addSubview:self.previousButton];
    [self.view addSubview:self.nextButton];
    [self.view addSubview:self.staticsBottomView];
    
    [self.menuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(kNavBarAndStatusBarHeight);
        make.height.mas_equalTo(46.0f);
    }];
    
    [self.calendar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(.0f);
        make.right.equalTo(self.view).offset(-10.0f);
        make.top.equalTo(self.menuView.mas_bottom).offset(13.0f);
        make.height.mas_equalTo(282);
    }];
    
    [self.previousButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.calendar).offset(95.0f);
        make.centerY.equalTo(self.calendar.mas_top).offset(27.0f);
        make.size.mas_equalTo(CGSizeMake(10, 8.5));
    }];

    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.calendar).offset(-95.0f);
        make.centerY.equalTo(self.calendar.mas_top).offset(27.0f);
        make.size.mas_equalTo(CGSizeMake(10, 8.5));
    }];
    
    [self.staticsBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(10.0f);
        make.right.equalTo(self.view).offset(-10.0f);
        make.top.equalTo(self.calendar.mas_bottom);
        make.bottom.equalTo(self.view);
    }];
    

}


#pragma mark - FSCalendarDataSource && FSCalendarDelegate
- (NSString *)calendar:(FSCalendar *)calendar titleForDate:(NSDate *)date{
    return [self.gregorian isDateInToday:date] ? @"今天" : nil;
}
- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date{
    return [self.lunarFormatter stringFromDate:date];
}

- (FSCalendarCell *)calendar:(FSCalendar *)calendar cellForDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{

    NSString *dateString = [self.dateFormatter stringFromDate:date];
    if ([self.normalArr containsObject:dateString]) {
        ZYCCalendarCell *cell = [calendar dequeueReusableCellWithIdentifier:@"cell" forDate:date atMonthPosition:monthPosition];
        cell.statusLabel.textColor = HEX_RGB(@"#41B166");
        cell.statusLabel.text = @"正常";
        return cell;
    }
    if ([self.exceptArr containsObject:dateString]) {
        ZYCCalendarCell *cell = [calendar dequeueReusableCellWithIdentifier:@"cell" forDate:date atMonthPosition:monthPosition];
        cell.statusLabel.textColor = HEX_RGB(@"#EC4402");
        cell.statusLabel.text = @"异常";
        return cell;
    }
    if ([self.workOvertimeArr containsObject:dateString]) {
        ZYCCalendarCell *cell = [calendar dequeueReusableCellWithIdentifier:@"cell" forDate:date atMonthPosition:monthPosition];
        cell.statusLabel.textColor = HEX_RGB(@"#39B5A0");
        cell.statusLabel.text = @"加班";
        return cell;
    }
    return nil;
}


- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date{
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    if ([self.normalArr containsObject:dateString]) {
        return 1;
    }
    if ([self.exceptArr containsObject:dateString]) {
        return 1;
    }
    if ([self.workOvertimeArr containsObject:dateString]) {
        return 1;
    }else{
        return 0;
    }
}


- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    NSLog(@"did select %@",[self.dateFormatter stringFromDate:date]);
    NSString *timeStr = [self.dateFormatter stringFromDate:date];
    self.attendanceDate = timeStr;
    [self loadDayStatistics];
    
}
// 切换月份
- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar{
    NSString *dateString = [self.dateFormatter stringFromDate:calendar.currentPage];
    self.attendanceDate = dateString;
    [self loadDayStatistics];
}

- (NSArray<UIColor *> *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance eventSelectionColorsForDate:(nonnull NSDate *)date{
    NSString *dateString = [self.dateFormatter stringFromDate:date];
    if ([self.normalArr containsObject:dateString]) {
        return @[HEX_RGB(@"#41B166")];
    }
    if ([self.exceptArr containsObject:dateString]) {
        return @[HEX_RGB(@"#EC4402")];
    }
    if ([self.workOvertimeArr containsObject:dateString]) {
        return @[HEX_RGB(@"#39B5A0")];
    }
    return nil;
}


#pragma mark - PullDownMenuViewDataSource
// 返回下拉菜单每列按钮标题
- (NSString *)pullDownMenu:(PullDownMenuView *)pullDownMenu titleForColAtIndex:(NSInteger)index {
    return [self.titleArr objectAtIndex:index];
}

// 返回下拉菜单每列对应的控制器
- (UIViewController *)pullDownMenu:(PullDownMenuView *)pullDownMenu viewControllerForColAtIndex:(NSInteger)index {
    ZYCPullDownMenuViewController *v = [self.viewControlls objectAtIndex:index];
    v.array = self.postArr.mutableCopy;
    return v;
}

// 返回下拉菜单多少列
- (NSInteger)numberOfColsInMenu:(PullDownMenuView *)pullDownMenu {
    return self.viewControlls.count;
}
- (CGFloat)pullDownMenu:(PullDownMenuView *)pullDownMenu heightForColAtIndex:(NSInteger)index {
    return 220.0f;
}

#pragma mark - getters
- (NSArray *)normalArr {
    if (!_normalArr) {
        _normalArr = [[NSArray alloc] init];
    }
    return _normalArr;
}

- (NSArray *)exceptArr {
    if (!_exceptArr) {
        _exceptArr = [[NSArray alloc] init];
    }
    return _exceptArr;
}

- (NSArray *)workOvertimeArr {
    if (!_workOvertimeArr) {
        _workOvertimeArr = [[NSArray alloc] init];
    }
    return _workOvertimeArr;
}
- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}
- (UIButton *)previousButton {
    if (!_previousButton) {
        _previousButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_previousButton setImage:[UIImage imageNamed:@"zuo"] forState:UIControlStateNormal];
        [_previousButton addTarget:self action:@selector(previousClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _previousButton;
}

- (UIButton *)nextButton {
    if (!_nextButton) {
        _nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextButton setImage:[UIImage imageNamed:@"you"] forState:UIControlStateNormal];
        [_nextButton addTarget:self action:@selector(nextClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextButton;
}


- (NSArray *)postArr {
    if (!_postArr) {
        _postArr = [NSArray array];
    }
    return _postArr;
}

- (NSArray *)titleArr {
    if (!_titleArr) {
        _titleArr = @[self.postName];
    }
    return _titleArr;
}

- (NSArray *)viewControlls {
    if (!_viewControlls) {
        _viewControlls = @[[NSClassFromString(@"ZYCPullDownMenuViewController") new]];
    }
    return _viewControlls;
}

- (FSCalendar *)calendar {
    if (!_calendar) {
        _calendar = [[FSCalendar alloc] init];
        _calendar.delegate = self;
        _calendar.dataSource = self;
        _calendar.headerHeight = 50.0f;
        _calendar.locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
        _calendar.appearance.headerMinimumDissolvedAlpha = 0;
        _calendar.backgroundColor = [UIColor whiteColor];
        _calendar.placeholderType = FSCalendarPlaceholderTypeNone; //只显示当前月份
        _calendar.appearance.headerDateFormat = @"yyyy年MM月";// 设置头部时间格式
        _calendar.appearance.weekdayTextColor = HEX_RGB(@"#62676A");//设置周字体颜色
        _calendar.appearance.headerTitleColor = HEX_RGB(@"#262A28");//设置头字体颜色
        _calendar.appearance.caseOptions = FSCalendarCaseOptionsHeaderUsesUpperCase|FSCalendarCaseOptionsWeekdayUsesSingleUpperCase;
//        _calendar.appearance.eventDefaultColor = HEX_RGB(@"#CECECE");// 设置日期下的小点点颜色
        _calendar.appearance.selectionColor = FSCalendarStandardTodayColor; // 设置点击某日某日的颜色
        _calendar.appearance.todayColor = FSCalendarStandardTodayColor;// 设置今天颜色
        [_calendar registerClass:[ZYCCalendarCell class] forCellReuseIdentifier:@"cell"];
    }
    return _calendar;
}

- (PullDownMenuView *)menuView {
    if (!_menuView) {
        _menuView = [[PullDownMenuView alloc] init];
//        _menuView.dataSource = self;
        _menuView.separateLineColor = [UIColor clearColor];
        _menuView.titleFont = kCustomFont(@"PingFangSC-Regular", 15.0f);
    }
    return _menuView;
}


- (BTImageTitleButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [[BTImageTitleButton alloc] init];
        [_rightButton setImage:[UIImage imageNamed:@"shuju"] forState:UIControlStateNormal];
        [_rightButton setTitle:@"考勤汇总" forState:UIControlStateNormal];
        [_rightButton setTitleColor:HEX_RGB(kTitleWhiteColor) forState:UIControlStateNormal];
        _rightButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_rightButton addTarget:self action:@selector(clickRightItem:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}

- (ZYCSchoolAttendanceStaticsBottomView *)staticsBottomView {
    if (!_staticsBottomView) {
        _staticsBottomView = [[ZYCSchoolAttendanceStaticsBottomView alloc] init];
    }
    return _staticsBottomView;
}

#pragma mark - action method
- (void)clickRightItem:(UIButton *)sender{
    ZYCAttendanceSummaryViewController *vc =[[ZYCAttendanceSummaryViewController alloc] init];
    vc.attendanceDate = self.attendanceDate;
    vc.postId = self.postId;
    vc.postName = self.postName;
    vc.postArr = self.postArr;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)previousClicked:(UIButton *)sender{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *previousMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:-1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:previousMonth animated:YES];
}

-(void)nextClicked:(UIButton *)sender{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *nextMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:nextMonth animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
